import vue from 'vue'
import VueRouter from 'vue-router'
import routes from './routes'
//读取token函数引入
import { gettoken,deletetoken } from '@/utils/auth'
//引入vuex
import store from '@/store'
vue.use(VueRouter)

const originalPush = VueRouter.prototype.push

const originalReplace = VueRouter.prototype.replace
// 重复跳转方法增强
VueRouter.prototype.push = function (location, onSuccess, onError) {
  if (onSuccess === undefined) {
    // 说明没有
    onSuccess = () => {}
    onError = () => {}
  }
  return originalPush.call(this, location, onSuccess, onError)
}

VueRouter.prototype.replace = function (location, onSuccess, onError) {
  if (onSuccess === undefined) {
    onSuccess = () => {}
    onError = () => {}
  }
  originalReplace.call(this, location, onSuccess, onError)
}

const router = new VueRouter({
  mode: 'history',
  routes
})

//这些路由登录后才能看
const Globalguard = ['/personal','/cart']

//全局导航守卫
router.beforeEach(async(to,from,next)=>{
  const token = gettoken()
  const {Personalinfo} = store.state.user
  if(token){
    if(Personalinfo.id){
      next() //放行
    }else{
      try {
        await store.dispatch('getinfo')
        next() //放行
      } catch (error) {
        deletetoken()
        next('/login')
      }
    }
  }else{
    if(Globalguard.includes(to.path)){
      next('/login')
    }else{
      next()
    }
  }
})


export default router